<?php
namespace ESTool;
/**
 * es 格式化输出
 * @author xianfei@leju.com
 */
class Format {
    /**
     * 合并数据
     * @param array $data    多个数据结果
     * @param array $group    合并是使用的key
     * @return array
     */
    static public function merge_index_data($data, $group) {
        $common_keys = call_user_func_array('array_intersect_key', $group);
        foreach ($data as $index => $list) {
            foreach ($list as $item) {
                $common_key_value = array_intersect_key((array)$item, $common_keys);
                ksort($common_key_value);
                $key = serialize($common_key_value);
                // 房源坐标特殊情况
                if (isset($common_key_value['house_geo']) && isset($item['geo'])) {
                    $common_key_value['geo'] = $item['geo'];
                    unset($item['geo']);
                }
                if (isset($common_key_value['house_geo']) && isset($item['distance'])) {
                    $common_key_value['distance'] = $item['distance'];
                    unset($item['distance']);
                }
                isset($result[$key]) || $result[$key] = $common_key_value;
                $result[$key][$index] = array_diff_key($item, $common_keys);
            }
        }
        return $result;
    }
    /**
     * 得分 
     */
    static public function source($item, $type='pv^house') {
        $source = false;
         
        if ($type=='house^pv') {
            if (isset($item['esf_bi_access*']['pv']) && isset($item['esf_bi_house_op*']['houseid'])) {
                $source = $item['esf_bi_house_op*']['houseid'] / $item['esf_bi_access*']['pv'];
                $source = $source * 10;
                $radius = $item['esf_bi_access*']['pv'];
                $count = $item['esf_bi_house_op*']['houseid'];
            }
        } elseif ($type=='pv^house') {
            if (isset($item['esf_bi_access*']['pv']) && isset($item['esf_bi_house_op*']['houseid'])) {
                $source = $item['esf_bi_access*']['pv'] / $item['esf_bi_house_op*']['houseid'];
                $source = $source * 10;
                $count = $item['esf_bi_access*']['pv'];
                $radius = $item['esf_bi_house_op*']['houseid'];
            }
        } elseif ($type=='house') {
            $source = $item['esf_bi_house_op*']['houseid'];
            $count = $source;
            $radius = 30;
        } elseif ($type=='pv') {
            $source = $item['esf_bi_access*']['pv'];
            $count = $source;
            $radius = 30;
        } elseif ($type=='lejuglobal') {
            $source = $item['esf_bi_access*']['lejuglobal'];
            $count = $source;
            $radius = 30;
        }
         
        if ($source == false) {
            if (isset($item['pv'])) {
                $source = $item['pv'];
            } else {
                foreach ($item as $k => $v) {
                    if (strstr($k, '*') !== false) {
                        $source = $v['pv'];
                        break;
                    }
                }
            }
            $count = $source;
            $radius = 30;
        }
        return array($source, $count, $radius);
    }
    // ************************************************************
    // ************************************************************
    // ***************** 输出工具处理 ***********************************
    // ************************************************************
    // ************************************************************
    static function getTableArray($data, $columnFamily, $column, $rowkey, $fieldList_es, $langs = array()){
        $head = self::getHeader($data, $columnFamily, $column);
        $body = self::getTableBody($data, $columnFamily, $column, $rowkey);
        $langs = array(
            'city' => Dict_City::allCities()
        );
        $tableArray = '';
        foreach ($head as $group => $item) {
            $level = substr_count($group, "^");
            if (is_array($item)) {
                foreach ($item as $k => $c) {
                    $c == 'phpsessid' && $c = 'uv';
                    $tableArray['head'][$level + 1][$group . $k] = $c;
                }
                $cls[$group] = $item;
            } else {
                $tableArray['head'][$level][$group] = array(
                    "title" => end($v), "width" => $item
                );
            }
            
            $tableArray['head'][$level][$group] = array(
                "title" => end($v), "width" => count($item)
            );
        }
        
        foreach ($columnFamily as $k => $cf) {
            if (isset($langs[$cf])) {
                foreach ($tableArray['head'][$k] as & $city) {
                    if (is_array($city)) {
                        $city['title'] = $langs[$cf][$city['title']];
                    } else {
                        $city = $langs[$cf][$city];
                    }
                }
            }
            if (! isset($fieldList_es['cf']['data'][$cf]['title'])) {
                $fieldList_es['cf']['data'][$cf]['title'] = '';
            }
            array_unshift($tableArray['head'][$k], $fieldList_es['cf']['data'][$cf]['title']);
        }
        array_unshift($tableArray['head'][++ $k], '统计指标');
        
        foreach ($cls as $group => $cs) {
            foreach ($body as $body_group => $itemList) {
                isset($tableArray['body'][$body_group]) || $tableArray['body'][$body_group][] = $body_group;
                if (is_array($itemList)) {
                    foreach ($cs as $c) {
                        $c = isset($itemList[$group][$c]) ? $itemList[$group][$c] : 0;
                        $tableArray['body'][$body_group][] = $c;
                    }
                    $cls[$group] = $item;
                } else {
                    $tableArray['body'][$group][] = array(
                        "title" => $group, "width" => count($cls)
                    );
                }
            }
        }
        return array_values($tableArray['head'] + $tableArray['body']);
    }

    

    /**
     * 获取 表格 数组
     * @param array $data    查询结果数据 Elasticsearch::fetchTable() 结果
     * @param array $columnFamily    列族
     * @param array $column    列
     * @param array $rowkey    行
     * @param array $eslang    语言包
     * @return array
     */
    static function getTable($data, $columnFamily, $column, $rowkey, $eslang){
        $column = array_keys($column);
        $head = self::getHeader($data, $columnFamily, $column);
        $body = self::getTableBody($data, $columnFamily, $column, $rowkey);
        
        $columnFamily_keys = array_keys($columnFamily);
        $cls = $returnData = array();
        // 获取 展示内容每列数据 key
        foreach ($head as $group => $item) {
            if (is_array($item)) {
                $cls[$group] = $item;
            }
        }
        // 获取 table header 部分 数据 -- start
        foreach ($head as $group => $item) {
            $level = substr_count($group, "^");
            if (is_array($item)) {
                $width = count($item);
            } else {
                $width = $item;
            }
            
            $title = strrchr($group, "^");
            if ($title === false) {
                $title = $group;
            } else {
                $title = substr($title, 1);
            }
            isset($returnData['header'][$level]) || $returnData['header'][$level][] = '';
            $returnData['header'][$level][$group] = array(
                "title" => self::getValue($title), "width" => $width
            );
            
            if (is_array($item)) {
                isset($returnData['header'][$level + 1]) || $returnData['header'][$level + 1][] = '统计指标';
                foreach ($item as $c) {
                    $returnData['header'][$level + 1][] = self::getValue($c);
                }
            }
        }
        
        // 获取 table header 部分 数据 -- end
        
        // 获取 table body 部分 数组数据 -- start
        foreach ($cls as $group => $cs) {
            foreach ($body as $body_group => $itemList) {
                isset($returnData['body'][$body_group]) || $returnData['body'][$body_group][] = self::getValue($body_group);
                foreach ($cs as $c) {
                    $c = isset($itemList[$group][$c]) ? $itemList[$group][$c] : 0;
                    $returnData['body'][$body_group][] = self::getValue($c);
                }
                $cls[$group] = $item;
            }
        }
        // 获取 table body 部分 数组数据 -- end
        
        foreach (array_keys($columnFamily) as $level => $cf) {
            foreach ($returnData['header'][$level] as $number => $stat_cl) {
                if ($number === 0) {
                    if (isset($eslang[$cf]['name'])) {
                        $returnData['header'][$level][0] = array(
                            "title" => $eslang[$cf]['name'], "width" => count($rowkey)
                        );
                    }
                } elseif (is_array($stat_cl)) {
                    if (isset($eslang[$cf]['data'][$stat_cl['title']])) {
                        $returnData['header'][$level][$number]['title'] = $eslang[$cf]['data'][$stat_cl['title']];
                    }
                } else {
                    if (isset($eslang[$cf]['data'][$stat_cl])) {
                        $returnData['header'][$level][$number] = $eslang[$cf]['data'][$stat_cl];
                    }
                }
            }
        }
        
        $rowkey = array_keys($rowkey);
        $level = count($returnData['header']) - 1;
        unset($returnData['header'][$level][0]);
        foreach (array_reverse($rowkey) as $number => $key) {
            array_unshift($returnData['header'][$level], $key);
        }
        
        // 替换语言包显示文字 -- start
        foreach ($returnData['header'][$level] as $number => $stat_cl) {
            if (isset($eslang[$stat_cl]['name'])) {
                $returnData['header'][$level][$number] = $eslang[$stat_cl]['name'];
            }
        }
        
        if (isset($returnData['body'])) {
            foreach ($returnData['body'] as $nber => $stat_cl) {
                unset($returnData['body'][$nber][0]);
                $val_list = explode("^", $stat_cl[0]);
                foreach ($rowkey as $number => $key) {
                    if (isset($val_list[$number])) {
                        $val = $val_list[$number];
                        if (isset($eslang[$key]['data'][$val])) {
                            $val = $eslang[$key]['data'][$val];
                        }
                    } else {
                        $val = '无';
                    }
                    $val_list[$number] = $val === '' ? '空' : $val;
                }
                foreach (array_reverse($val_list) as $val) {
                    array_unshift($returnData['body'][$nber], $val);
                }
            }
        } else {
            $returnData['body'] = array();
        }
        // 替换语言包显示文字 -- end
        return $returnData;
    }
    /**
     * 获取 表格 html 格式
     * @param array $data    查询结果数据 Elasticsearch::fetchTable() 结果
     * @param array $columnFamily    列族
     * @param array $column    列
     * @param array $rowkey    行
     * @param array $eslang    语言包
     * @return array
     */
    static function getTableHtml($data, $columnFamily, $column, $rowkey, $eslang){
        $returnData = self::getTable($data, $columnFamily, $column, $rowkey, $eslang);
        // 原生 table - start
        $body = $head = '';
        if (isset($returnData['header'])) {
            foreach ($returnData['header'] as $rowkey => $row) {
                $head .= "<tr>";
                foreach ($row as $cl) {
                    if (is_array($cl)) {
                        $cl = sprintf("<td colspan='%d'>%s</td>", $cl['width'], $cl['title']);
                    } else {
                        $cl = sprintf("<td>%s</td>", $cl);
                    }
                    $head .= $cl;
                }
                $head .= "</tr>";
            }
        }
        if (isset($returnData['body'])) {
            foreach ($returnData['body'] as $level => $h) {
                $body .= "<tr><td>" . implode("</td><td>", $h) . "</td></tr>";
            }
        }
        $tableHtml = '<div class="table-responsive" style="overflow: auto; height: 600px;">';
        $tableHtml .= '<table class="table table-striped table-bordered hover">';
        $tableHtml .= $head;
        $tableHtml .= $body;
        $tableHtml .= "</table>";
        $tableHtml .= '</div>';
        // 原生 table - end
        return $tableHtml;  
    }

    /**
     * 获取表格Body内容 - 内部方法
     */
    static protected function getTableBody($data, $columnFamily, $column, $rowkey){
        $body = array();
        if ($data) {
            foreach ($data as $item) {
                $rowkey_s = array();
                if (! is_array($rowkey) || empty($rowkey)) {
                    break;
                }
                $rowkey_s = implode("^", array_intersect_key((array)$item, $rowkey));
                $columnFamily_s = implode("^", array_intersect_key((array)$item, $columnFamily));
                foreach ($column as $c) {
                    $body[$rowkey_s][$columnFamily_s][$c] = self::getValue($item[$c]);
                }
            }
        }
        return $body;
    }

    /**
     * 获取表格 Header 内容 - 内部方法
     */
    static protected function getHeader($data, $columnFamily, $column){
        $head = array();
        if ($data) {
            foreach ($data as $item) {
                $columnFamily_s = array();
                foreach ($columnFamily as $cfk => $cf) {
                    $columnFamily_s[] = $item[$cfk];
                    if ($cf == end($columnFamily)) {
                        $head[implode("^", $columnFamily_s)] = $column;
                    } else {
                        $head[implode("^", $columnFamily_s)] = '';
                    }
                }
            }
        }
        $cls = count($columnFamily) * count($column);
        $max_level = count($columnFamily) - 1;
        foreach ($head as $k => $v) {
            if (substr_count($k, "^") != $max_level) {
                $count = 0;
                foreach ($head as $k2 => $v2) {
                    if (substr_count($k2, "^") == $max_level && strpos("^" . $k2 . "^", "^" . $k . "^") === 0) {
                        $count ++;
                    }
                }
                $head[$k] = $count * count($column);
            }
        }
        ksort($head);
        return $head;
    }
    
    static function getValue($text){
        return trim(urldecode($text));
    }
    /**
     * 获取数组值，然后过滤空值
     * @param array $data
     * @return array
     */
    static function filterTableData($data) {
        $data = array_filter($data, function ($a){
            return !empty($a);
        });
        $data = array_values($data);
        return $data;
    }
    
}